import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
import { mapMutations } from 'vuex'

const methods = mapMutations(['setLogin', 'setUserInfo', 'setLoginDialog'])

// 网站根路径
let rootUrl = window.localStorage.rootUrl || ''

if (window.localStorage.rootUrl != null && window.localStorage.rootUrl !== undefined) {
    rootUrl = window.localStorage.rootUrl
}

// 实例
let instance

const api = {
    rootUrl: rootUrl
}

// 重新加载实例
const reLoadInstance = function () {
    if (window.localStorage.rootUrl != null && window.localStorage.rootUrl !== undefined) {
        rootUrl = window.localStorage.rootUrl
    }
    window.console.log('重新加载实例', rootUrl, {
        __userId: window.localStorage.getItem('userId'),
        __token: window.localStorage.getItem('token')
    })
    instance = axios.create({
        time: 1000 * 60,
        withCredentials: true,
        baseURL: rootUrl,
        adapter: '',
        headers: {
            __userId: window.localStorage.getItem('userId'),
            __token: window.localStorage.getItem('token')
        }
    })
    instance.defaults.withCredentials = true
    instance.defaults.validateStatus = function () {
        return true
    }
    // 添加请求拦截器
    instance.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        return config
    }, function (error) {
        // 对请求错误做些什么
        Message.error({ message: '请求超时!' })
        return Promise.reject(error)
    })
    // 添加响应拦截器
    instance.interceptors.response.use(function (response) {
        const status = response.status
        // 在发送请求之前做些什么
        if (status === 200) {
            return Promise.resolve(response)
        } else if (status === 301) {
            Message.error({ message: '请先登录网易云!' })
            // router.replace({
            //     path: 'login'
            // })
            return false
        } else if (status === 401) {
            Message.error({ message: '请先登录!' })
            console.log('[信息]401鉴权错误', status, process.env.NODE_ENV)
            window.localStorage.removeItem('isLogin')
            window.localStorage.removeItem('token')
            window.localStorage.removeItem('userInfo')
            window.localStorage.removeItem('token')
            window.localStorage.removeItem('userId')
            window.localStorage.removeItem('LOGIN_RESULT')
            methods.setLogin(false)
            methods.setUserInfo()
            if (process.env.NODE_ENV === 'development') {
                router.replace({
                    path: 'login'
                })
            } else {
                if ((typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]')) {
                    this.$msg.success('退出成功')
                    router.replace({
                        path: 'login'
                    })
                } else if (typeof XMLHttpRequest !== 'undefined') {
                    // web 环境下
                    window.location.href = '/login.html'
                }
            }
            return false
        } else {
            return Promise.reject(response)
        }
    }, function (error) {
        // 对请求错误做些什么
        Message.error({ message: '网络错误!' })
        return Promise.reject(error)
    })
    const ajaxMethod = ['get', 'post']
    ajaxMethod.forEach(method => {
        // 数组取值的两种方式
        api[method] = function (uri, data, config) {
            return new Promise(function (resolve, reject) {
                instance.post('/api/music/getWyyApi', {
                    url: uri,
                    method: method,
                    data: data
                }, config)
                .then(response => {
                    if (response.status === 200) {
                        resolve(response)
                    }
                })
                .catch(error => {
                    reject(error)
                })
            })
        }
    })
    api.rootUrl = rootUrl
    api.instance = instance
}

// 初始化
reLoadInstance()
api.reLoadInstance = reLoadInstance
api.instance = instance

export default api
